#!/usr/bin/python
# -*- coding: utf-8 -*-

"""
#TODO: documentation!
"""

__version__ = '$Id: engine.py 196 2008-03-04 03:10:05Z DLacewell $'

import psp2d
from bipy.components import *

class EngineClass(Dynamic):
    def __init__(self, *args, **named):
        super(EngineClass, self).__init__(*args, **named)
        # scene attributes
        self.__scenes = []
        evt_comp = get('eventmanager')
        self.add_component( evt_comp() )
        scr_comp = get('pspscreen')
        self.add_component( scr_comp(color=(255,0,0)) )
        ctr_comp = get('pspcontroller')
        self.add_component( ctr_comp() )
        
    def get_current_scene(self):
        return self.__scenes[-1]
        
    def register_listeners(self):
        """
        Registers all event handlers for the topmost state.
        """
        signalmatrix = self.__scenes[-1].get_signal_matrix()
        print signalmatrix
        for signal in signalmatrix:
            try:
                self.events.signals[signal].register(signalmatrix[signal])
            except KeyError:
                print r'Engine: couldn\'t find a "%s" signal for event registration.' % signal
                
    def unregister_listeners(self):
        """
        Unregisters all event handlers for the topmost state.
        """
        print self.__scenes
        signalmatrix = self.__scenes[-1].get_signal_matrix()
        for signal in signalmatrix:
            try:
                self.events.signals[signal].unregister(signalmatrix[signal])
            except KeyError:
                print r'Engine: couldn\'t find a "%s" signal for event unregistration.' % signal
    
    def push_scene(self, scene):
        """
        Enter a new Scene. (Automatic event registration and unregistration)
        """
        if len(self.__scenes):
            self.unregister_listeners()
        self.__scenes.append(scene)
        self.register_listeners()
        self.__scenes[-1].enter()
        
    def pop_scene(self):
        """
        Leave current Scene. (Automatic event registration and unregistration)
        """
        if len(self.__scenes):
            self.unregister_listeners()
            self.__scenes[-1].leave()
            del self.__scenes[-1]
        if len(self.__scenes):
            self.register_listeners()
            return True
        return False
                
    def get_num_scenes(self):
        # Frozen scenes and the running scene
        return len(self.__scenes)

    def clear_scenes(self):
        # Pop each scene
        while len(self.__scenes): self.pop_scene()

    def run(self, scene):
        # Push initialized scene object
        self.push_scene( scene )
        # Run while there is a scene on the stack
        while self.__scenes:
            self.events.dispatch()
            self.screen.swap()

    def on_close(self):
        self.clear_scenes()
